import {
  Controller,
  Post,
  Get,
  UseInterceptors,
  UploadedFile,
  Param,
  Res,
  BadRequestException,
  NotFoundException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express'; // 处理文件上传的拦截器
import { Response } from 'express';
import { FileService } from './file.service';
import { join } from 'path';
import * as fs from 'fs';
import { Public } from '../../../../../common/public.decorator';

@Controller('file')
export class FileController {
  constructor(private readonly fileService: FileService) {}
  @Public()
  @Post('uploadToServer')
  @UseInterceptors(FileInterceptor('file')) // 拦截器处理 'file' 参数的文件上传
  async upload(@UploadedFile() file: any): Promise<any> {
    return this.fileService.uploadFileToServer(file);
  }

  @Public()
  @Get('downloadFiles/:filename')
  async downloadFiles(
    @Param('filename') filename: string,
    @Res() res: Response,
  ): Promise<any> {
    const filePath = join(__dirname, `../../../assets/${filename}`);
    if (!fs.existsSync(filePath)) {
      throw new BadRequestException('file no found');
    }
    res.download(filePath, (err) => {
      if (err) {
        throw new BadRequestException(err);
      }
    });
  }

  @Public()
  @Get('downloadFilestoStream/:filename')
  async streamFile(@Param('filename') filename: string, @Res() res: Response) {
    try {
      const filePath = join(__dirname, `../../../assets/${filename}`);
      if (!fs.existsSync(filePath)) {
        throw new NotFoundException('File not found');
      }
      // 设置响应头
      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
      // 创建文件读取流
      const readStream = fs.createReadStream(filePath);
      // 错误处理
      readStream.on('error', (err) => {
        throw new BadRequestException(err);
      });
      // 流式传输文件到响应
      readStream.pipe(res);
    } catch (error) {
      throw new BadRequestException(error);
    }
  }
}
